package com.qfjy.controller;

import com.qfjy.common.utils.excel.ExcelUtils;
import com.qfjy.common.utils.redis.RedisRepeatUtils;
import com.qfjy.common.utils.result.ResultCode;
import com.qfjy.common.utils.result.ResultJson;
import com.qfjy.entity.po.User;
import com.qfjy.entity.vo.UserVO;
import com.qfjy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author guoweixin
 * @Date 2022/11/28
 * @Version 1.0
 */
@Controller
@RequestMapping("user")
@Slf4j
@Api(tags = {"用户列表"})
public class UserController {

    /**Redis工具类集成 去重（Redis解决非幂等性）*/
    @Autowired
    private RedisRepeatUtils redisRepeatUtils;
    @Autowired
    private UserService userService;
    //列表查找
    @GetMapping("list")
    public String list(HttpServletRequest request){

       List<User> list= userService.selectList();
       request.setAttribute("list",list);
        return "user/list";
    }

    //列表条件查找
    @GetMapping("listCondition")
    public String listCondition(HttpServletRequest request, UserVO userVO){

        List<User> list= userService.listCondition(userVO);


        request.setAttribute("name",userVO.getName());
        request.setAttribute("rid",userVO.getRid());
        request.setAttribute("startTime",userVO.getStartTime());
        request.setAttribute("endTime",userVO.getEndTime());
        request.setAttribute("list",list);
        return "user/list";
    }


    /**
     * TODO 进入导入数据 页面
     */

    @GetMapping("importExcelToPage")
    public String importExcelToPage(HttpServletRequest request){

        // redis生成key
        String key="user:importExcel:";
        redisRepeatUtils.generateToken(key,request);

        return "user/importExcel";
    }

    /**
     * TODO Excel导入功能
     *  1、解析excel数据 读取Java对象。
     *  2、存入MyBatis数据（批量添加）[根据邮箱进行数据去重功能】
     */
    @ApiOperation(value = "导入功能",notes = "解析excel数据 读取Java对象")
    @ResponseBody
    @PostMapping("importExcel")
    public Object importExcel(@RequestParam("file2")MultipartFile file,HttpServletRequest request){

        log.info("请求进来了---》");
        //Redis进行前端和后台redis key进行比较（判断是否是重复提交）
       // user:importExcel:
       boolean flag= redisRepeatUtils.repeatCheck("user:importExcel:",request);
       if(flag==false){
           log.warn("此次请求是重复提交");
           return 0;
       }

        int num=0;
        try {
            //1、解析excel数据
            List<User> list=  ExcelUtils.importExcel(file,User.class);
            log.info("导入数据成功{}",list);




            //2、去重数据业务逻辑
            //           // list=this.repeatEmailDate(list);

            //2、批量添加MYSQL
            if(list.size()>0) {
                num = userService.insertBatch(list);

             log.info("批量添加成功{}",num);
            }


        } catch (Exception e) {
            //e.printStackTrace();
            log.error(e.getMessage());
        }
        return num;
    }

    /**
     * TODO 去重方法
     */
    public List<User> repeatEmailDate(List<User> excelLists){
        //查询数据库所有的email查询  Redis set类型中
        List<String> listDBEmails= userService.selectListEmail();

        for(int i=0;i<excelLists.size();i++){

            User u=excelLists.get(i);

            if(listDBEmails.contains(u.getEmail())){
                excelLists.remove(u);
                i--;
            }
        }

        return excelLists;
    }


    /**
     * TODO 导出功能
     */
    @RequestMapping("export")  //user/export
    public  void exportExcel(HttpServletResponse response, UserVO userVO) throws IOException {

        List<User> list= userService.listCondition(userVO);

        ExcelUtils.exportExcel(list,"用户信息列表","用户信息",User.class,"用户信息文件",response);
    }



    /**
     * TODO 删除
     * 测试：可通过postman / swagger等进行在线接口测试
     */
    @ApiOperation(value = "删除功能",notes = "根据ID进行删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true,defaultValue = "1")
    })
    @PostMapping("deleteUserById")
    @ResponseBody
    public Object deleteUserById(@RequestParam("id") final int id){

       int num= userService.deleteByPrimaryKey(id);
       log.info("删除成功{}",num);
        return num;
    }
    /**
     * TODO 批量删除
     * @param idStr  1,2,3,4,5,
     */
    @ApiOperation(value = "批量删除功能",notes = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idStr", value = "批量删除多个id集合，用,分隔", required = true,defaultValue = "1,2,3,")
    })
    @ResponseBody
    @PostMapping("deleteBatch")
    public Object deleteBatch(@RequestParam("idStr") String idStr){

        String[] ids=idStr.split(",");
        int num= userService.deleteBatch(ids);
        log.info("批量删除成功{}",num);
        return new ResultJson<>(num,ResultCode.SUCCESS);
    }

    /**
     * TODO 查询  根据ID查询用户信息
     */
    @ApiOperation(value = "根据ID查询用户信息",notes = "根据ID查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键ID", required = true)
    })
    @ResponseBody
    @GetMapping("selectById")
    public  Object selectByPrimaryKey(@RequestParam("id") Integer id){

        User user=userService.selectByPrimaryKey(id);
        if(user==null){
            return new ResultJson<>(null, ResultCode.NOT_DATA);
        }
        return new ResultJson<>(user,ResultCode.SUCCESS);
    }


    /**
     * TODO 状态修改，根据ID
     */
    @ApiOperation(value = "状态修改，根据ID")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "状态0无效 1有效", required = true),
            @ApiImplicitParam(name = "id", value = "主键ID", required = true)
    })
    @ResponseBody
    @GetMapping("updateStatusById")
    public Object  updateStatusById(@RequestParam("status") final int status,
                                    @RequestParam("id") final int id){
        int num=userService.updateUserStatusById(status,id);
        log.info("状态修改成功{}，{}",status,id);
        return new ResultJson<>(num,ResultCode.SUCCESS);
    }
}
